﻿

var mEvidenceBill = {};//物品记录对象
var mEvidences = [];
var mEvidenceBill_User; //当前用户

var mEvidenceDlg; //物品明晰对话框

var mCaseFileQuery = {};

var mDlgAttachment;
var mEviEstimate;
$(function () {
    try {
        $('#evidenceDiv').mask('正在加载单据...');
        extendEasyUI();

        var args = getUrlArgs();
        var evidenceBillId = args["evidenceBillId"];

        mEvidenceBill_User = gGetLoginUser();//获取当前登录用户

        var evidenceQuery = {};
        evidenceQuery.BillId = evidenceBillId;

        $('#detailDataGrid').datagrid({
            //url: '/Case/LoadEvidenceList',
            //queryParams: { 'evidenceQuery': JSON.stringify(evidenceQuery) },
            fitColumns: true,
            rownumbers: true,
            resizable: true,
            pagination: false,
            nowrap: false,
            height: 140,
            idField: 'Id',
            singleSelect: true,
            toolbar: "#evidenceToolBar",
            onDblClickRow: viewEvidence,
            columns: [[
                   { title: 'Id', field: 'Id', align: 'left', width: 5, hidden: true },
                   { title: '类型', field: 'EvidenceType', align: 'left', width: 120, formatter: gGetPropertyName },
                   { title: '名称', field: 'Name', align: 'left', width: 120 },
                   { title: '型号', field: 'Model', align: 'left', width: 120 },
                   { title: '数量', field: 'Qty', align: 'left', width: 80 },
                   { title: '金额', field: 'Amount', align: 'left', width: 100 },
                   { title: '所有人', field: 'OwnerName', align: 'left', width: 100 },
                   { title: '扣押来源', field: 'Origin', align: 'left', width: 100, formatter: gGetPropertyName }
            ]]
        });


        $("#cmbTransferDept").combobox({
            valueField: 'Id',
            textField: 'Name',
            editable: false,
            disabled: true,
            panelWidth: 200,
            onSelect: selTransferDept
        });

        $("#cmbCaseCategory").combobox({
            valueField: 'Id',
            textField: 'Name',
            editable: false,
            panelHeight: "auto",
            onSelect: function (record) { mEvidenceBill.Category = record; }
        });

        //$("#cmbTransfer").combobox({
        //    valueField: 'Id',
        //    textField: 'Name',
        //    editable: false,
        //    onSelect: function (record) { mEvidenceBill.Transfer = record; }
        //});

        $('#cmbManageDept').combobox({
            valueField: 'Id',
            textField: 'Name',
            //panelHeight: "auto",
            panelWidth: 200,
            formatter: function (row) { return gFormatDeptName(row.Name); },
            editable: false,
            onSelect: onManageDeptSelected //设置管理部门
        });

        initEvidenceBill(evidenceBillId);

        loadBaseData();

        //loadTransfers(mEvidenceBill.TransferDept.Id); //根据登录人/单据部门动态加载用户

        var stockQuery = {};
        stockQuery.BillType = -1;
        stockQuery.CheckState = -1;
        stockQuery.CaseId = mEvidenceBill.Id;

        $('#stockBillDataGrid').datagrid({
            url: '/Case/LoadStockBillSimpleListForEvidenceBill',
            fitColumns: true,
            rownumbers: true,
            resizable: true,
            pagination: true,
            pageNumber: 1,
            pageSize: 8,
            pageList: [8],
            showPageList: false,
            nowrap: false,
            height: 260,
            idField: 'Id',
            //toolbar: '#stockBillToolbar',
            queryParams: { 'stockBillList_Query': JSON.stringify(stockQuery) },
            singleSelect: true,
            
            columns: [[
                   { title: 'Id', field: 'Id', align: 'left', width: 10, hidden: true },
                   { title: '日期', field: 'BillTime', align: 'left', width: 100, formatter: getFormatDate },
                   { title: '单据类型', field: 'BillType', align: 'left', width: 100, formatter: getFormatBillType },
                   { title: '状态', field: 'IsCheck', align: 'left', width: 50, formatter: getCheckState },
                   { title: '办案单位', field: 'TransferDeptName', align: 'left', width: 130, formatter: gFormatDeptNameForColumn },
                   { title: '办案人', field: 'TransferName', align: 'left', width: 80 }


            ]]
        });

        var StorageEvidenceList_Query = {};
        StorageEvidenceList_Query.QueryType = 1;
        StorageEvidenceList_Query.CaseId = mEvidenceBill.Id;

        $('#storageEvidenceGrid').datagrid({
            url: '/BaseData/LoadStorageEvidenceList',
            fitColumns: true,
            rownumbers: true,
            resizable: true,
            pagination: true,
            pageNumber: 1,
            pageSize: 8,
            pageList: [8],
            showPageList: false,
            nowrap: false,
            height: 260,
            idField: 'Id',
            //toolbar: '#stockBillToolbar',
            queryParams: { 'StorageEvidenceList_Query': JSON.stringify(StorageEvidenceList_Query) },
            singleSelect: true,
            //onDblClickRow: selStockRow,
            columns: [[
                   { title: 'Id', field: 'Id', align: 'left', width: 10, hidden: true },
                   { title: '保管单位', field: 'ManageDeptName', align: 'left', width: 100, formatter: gFormatDeptNameForColumn },
                   { title: '仓位', field: 'StorageName', align: 'left', width: 120 },
                   { title: '数量', field: 'Qty', align: 'right', width: 80 }
            ]]
        });

        display();



        $('#evidenceDiv').unmask();
    } catch (ex) {
        alert('错误提示:' + ex);
        $('#evidenceDiv').unmask();
    }
});

//选择办案单位
function selTransferDept(record) {

    if (record) {
        mEvidenceBill.TransferDept = record;
        //loadTransfers(record.Id);
    }
}

function caseFileDiscription() {

}

function formatDate(value, rowData, index) {
    if (value) {
        return gFormatDateFormCSharp(value, 'yyyy-MM-dd');
    }
}

function FormmatName(value, rowData, index) {
    return '<span><a  href="javascript:void(0);"  onclick="function()ClickFunction(' + rowData.Id + ')" sty>' + value + '</a></span>';
}

function buildCaseFileQuery() {
    var query = {};
    query.BillType = 1;
    query.BillId = mEvidenceBill.Id;

    return query;
}

//初始化当前单据
function initEvidenceBill(billId) {
    if (billId == 0) {
        mEvidenceBill.Id = 0; //新增
        mEvidenceBill.BillType = 1; //物品记录单
        mEvidenceBill.BillTime = gGetCurrentTime();
        mEvidenceBill.Department = mEvidenceBill_User.Department;
        mEvidenceBill.TransferDept = mEvidenceBill_User.Department; //默认等于制单部门
        mEvidenceBill.TransferName = mEvidenceBill_User.Name;            //默认等于制单人
        mEvidenceBill.Preparer = mEvidenceBill_User;
        mEvidenceBill.IsCheck = false;
        loadBillSerialNo();

    } else {
        loadEvidenceBill(billId);
    }
}
//获取下一个单据编号
function loadBillSerialNo() {
    $.ajax({
        url: '/Case/LoadNextBillSerialNo',
        type: "POST",
        dataType: "json",
        async: false,
        data: { "billType": 1 },
        success: function (req) {
            if (req.IsSuccess) {
                mEvidenceBill.SerialNo = req.Data;
            }
        },
    });
}

//读取单据信息
function loadEvidenceBill(billId) {
    $.ajax({
        url: "/Case/LoadEvidenceBill",
        type: "POST",
        dataType: "json",
        async: false,
        data: { "evidenceBillId": billId },
        success: function (req) {
            if (req.IsSuccess) {
                mEvidenceBill = JSON.parse(req.Bill);
                mEvidences = JSON.parse(req.Details);
                mEviEstimate = mEvidenceBill.CheckTime;
            }
        },
    });
}
//显示物品明细
function loadDetails() {
    $('#detailDataGrid').datagrid('loadData', mEvidences);
}

//显示物品记录
function display() {
    try {
        if (mEvidenceBill) {
            lockElements(mEvidenceBill.IsCheck);
        }

        $('#txtNumber').val(mEvidenceBill.Number);
        $('#txtSerialNo').val(mEvidenceBill.SerialNo);

        if (mEvidenceBill.Category) {
            $("#cmbCaseCategory").combobox("select", mEvidenceBill.Category.Id);
        }

        if (mEvidenceBill.TransferDept) {
            $("#cmbTransferDept").combobox("select", mEvidenceBill.TransferDept.Id);
            //loadTransfers(mEvidenceBill.TransferDept.Id)
        }

        $("#txtTransferName").val(mEvidenceBill.TransferName);

        //if (mEvidenceBill.Transfer) {
        //    $("#cmbTransfer").combobox("select", mEvidenceBill.Transfer.Id);
        //}

        $('#txtTransferPhone').val(mEvidenceBill.TransferPhone);
        $('#txtDescription').val(mEvidenceBill.Description);
        if (mEvidenceBill.ManageDept) {
            $("#cmbManageDept").combobox("select", mEvidenceBill.ManageDept.Id);
        }
        if (mEvidenceBill.Department) {
            $("#txtDepartment").val(gFormatDeptName(mEvidenceBill.Department.Name));
        }
        if (mEvidenceBill.Preparer) {
            $("#txtPreparer").val(mEvidenceBill.Preparer.Name);
        }
        $("#txtBillTime").val(gFormatDateFormCSharp(mEvidenceBill.BillTime));

        if (mEvidenceBill.CheckDept) {
            $("#txtCheckDept").val(gFormatDeptName(mEvidenceBill.CheckDept.Name));
        }

        if (mEvidenceBill.Checker) {
            $("#txtChecker").val(mEvidenceBill.Checker.Name);
        }

        if (mEvidenceBill.CheckTime) {
            $("#txtCheckTime").val(gFormatDateFormCSharp(mEvidenceBill.CheckTime));
        }

        loadDetails();

    } catch (ex) {
        alert("display:  " + ex);
    }
}

function lockElements(lock) {
    if (lock) {
        $('#txtNumber').attr("disabled", true);
        $('#cmbCaseCategory').combobox("disable");
        $('#cmbTransferDept').combobox("disable");
        $('#txtTransferName').attr("disabled", true);
        $('#txtTransferPhone').attr("disabled", true);
        $('#cmbManageDept').combobox("disable");
        $('#txtDescription').attr("disabled", true);
        $('#btnSaveEvidenceBill').hide();
        $('#btnAddEvidence').hide();
        $('#btnDelEvidence').hide();
        $('#txtTransferPhone').attr("disabled", true);
        //$('#txtTransferPhone').attr("disabled", true);
        //$('#txtTransferPhone').attr("disabled", true);
    }
}


function onManageDeptSelected(record) {
    mEvidenceBill.ManageDept = record;
}

//读取所有基本数据类型
function loadBaseData(user) {
    gLoadAllDepts(function (orgs) {
        $('#cmbTransferDept').combobox("loadData", orgs);
    });

    $('#cmbManageDept').combobox("loadData", loadOrgsByStorage());

    gLoadAllCaseCategories(function (ccs) { $('#cmbCaseCategory').combobox("loadData", ccs); });

}

//读取送交人
//function loadTransfers(deptId) {
//    var users = gLoadUserListByDeptId(deptId);
//    $('#cmbTransfer').combobox('loadData', users);
//    if (mEvidenceBill.Transfer && mEvidenceBill.Transfer.Department && mEvidenceBill.Transfer.Department.Id == mEvidenceBill.TransferDept.Id) {
//        $('#cmbTransfer').combobox('select', mEvidenceBill.Transfer.Id);
//    } else {
//        mEvidenceBill.Transfer = null;
//        $("#cmbTransfer").combobox("setValue", "");
//    }

//}

//保存物品单据
function saveEvidenceBillAction() {
    try {

        if (mEvidenceBill.IsCheck) {
            $.messager.alert('提示', '单据已经审核，不能再保存!');
            return;
        }

        $('#evidenceDiv').mask('正在保存物品记录单据...');


        mEvidenceBill.Number = $('#txtNumber').val();
        mEvidenceBill.TransferPhone = $('#txtTransferPhone').val();
        mEvidenceBill.TransferName = $('#txtTransferName').val();
        mEvidenceBill.Description = $("#txtDescription").val();
        if (checkEvidenceBill()) {
            var json = JSON.stringify(mEvidenceBill);
            var details = JSON.stringify(mEvidences);

            $.ajax({
                url: "/Case/SaveEvidenceBill",
                type: "POST",
                dataType: "json",
                data: { "evidenceBillJson": json, "detailsJson": details },
                async: false,
                success: function (req) {
                    if (req.IsSuccess) {
                        loadEvidenceBill(req.Data);
                        $.messager.alert('提示', '保存成功!');
                        display();

                    } else {
                        $.messager.alert('提示', req.Data, "warning");
                    }
                    $('#evidenceDiv').unmask();
                },
            });
        }
    } catch (ex) {
        alert(ex);
    } finally {
        $('#evidenceDiv').unmask();
    }
}

//检查物品单据
function checkEvidenceBill() {
    if (!mEvidenceBill.Number) {
        $.messager.alert('提示', '请录入案件编号!');
        return false;
    }

    if (!mEvidenceBill.Category) {
        $.messager.alert('提示', '请选择案件类型!');
        return false;
    }

    if (!mEvidenceBill.TransferDept) {
        $.messager.alert('提示', '请选择办案单位!');
        return false;
    }

    if (!mEvidenceBill.ManageDept) {
        $.messager.alert('提示', '请选择保管部门单位!');
        return false;
    }

    if (mEvidenceBill.TransferName == undefined || mEvidenceBill.TransferName == '' || mEvidenceBill.TransferName ==null) {
        $.messager.alert('提示', '请选择办案人!');
        return false;
    }

    var dcount = mEvidences.length;

    for (var i = 0; i < dcount; i++) {
        var detail = mEvidences[i];

        if (!detail.EvidenceType) {
            $.messager.alert('提示', '请选择物品:[ ' + detail.Name + ' ]的类型!');
            return false;
        }

        if (!detail.UM) {
            $.messager.alert('提示', '请选择物品:[ ' + detail.Name + ' ]的计量单位!');
            return false;
        }

        if (detail.Qty == 0) {
            $.messager.alert('提示', '物品:[ ' + detail.Name + ' ]的数量不能等于零!');
            return false;
        }

        if (!detail.OwnerName) {
            $.messager.alert('提示', '物品:[ ' + detail.Name + ' ]的联系人不能为空!');
            return false;
        }

        if (!detail.OwnerContact) {
            $.messager.alert('提示', '物品:[ ' + detail.Name + ' ]的联系方式不能为空!');
            return false;
        }
    }

    return true;
}

function getSelectEvidenceId() {
    var row = $("#detailDataGrid").datagrid("getSelected");
    var id = 0;
    if (row) {
        id = row.Id;
    }

    return id;
}

function viewEvidence() {
    editEvidenceAction();
}

//添加物品
function addEvidenceAction() {
    showEvidenceView(-1);//新增的index = -1
}
//编辑物品
function editEvidenceAction() {

    var row = $('#detailDataGrid').datagrid('getSelected');

    if (row) {
        var index = $('#detailDataGrid').datagrid('getRowIndex', row);
        showEvidenceView(index);
    } else {
        $.messager.alert('提示', '请选择需要查看的物品!');
    }
}

//删除物品
function delEvidenceAction() {
    var row = $('#detailDataGrid').datagrid('getSelected');
    if (row) {
        var index = $('#detailDataGrid').datagrid('getRowIndex', row);

        mEvidences.splice(index, index);

        loadDetails();

    } else {
        $.messager.alert('提示', '请选择需要查看的物品!');
    }
}
//显示物品子页面
function showEvidenceView(index) {
    try {
        var cTime= null;
        if (!mEvidenceBill.IsCheck) {
            var nt = new Date();
            cTime = nt.getTime();
        } else {
            if (mEviEstimate == undefined || mEviEstimate == "undefined") {
                var nttime = new Date();
                cTime = nttime.getTime();
            } else {
                cTime = eval('new ' + mEviEstimate.substring(1, mEviEstimate.length - 1)).getTime();
            }
        }
        mEvidenceDlg = art.dialog({
            title: '物品详细信息',
            content: "<iframe scrolling='yes' frameborder='0' src='/Case/EvidenceView?index=" + index + "&mEvidenceEstimate=" + cTime + "' style='width:560px;height:360px;'/>",
            lock: true,
            initFn: function () {
            }
        });
    } catch (ex) {
        alert(ex);
    }
}

//生成入库申请单
function checkBillAction() {
    try {
        if (mEvidenceBill.Id == undefined || mEvidenceBill.Id == 0) {
            $.messager.alert('提示', '请先保存物品单!');
        } else if (mEvidenceBill.IsCheck) {
            $.messager.alert('提示', '物品单已经提交过!');
        } else {
            $('#evidenceDiv').mask('正在提交单据...');
            $.ajax({
                url: "/Case/CheckEvidenceBill",
                type: "POST",
                async: false,
                dataType: "json",
                data: { "checkDeptId": mEvidenceBill_User.Department.Id, "checkerId": mEvidenceBill_User.Id, "billId": mEvidenceBill.Id },
                success: function (req) {
                    if (req.IsSuccess) {
                        loadEvidenceBill(mEvidenceBill.Id);
                        display();
                        $.messager.alert('提示', "审核成功!");
                    } else {
                        $.messager.alert('提示', req.Data, "warning");
                    }
                    $('#evidenceDiv').unmask();
                },
            });
        }

    } catch (ex) {

    } finally {
        $('#evidenceDiv').unmask();
    }
}


//打印物品详细信息单据
function printBillAction() {
    try {
        if (mEvidenceBill.Id == undefined || mEvidenceBill.Id == 0) {
            $.messager.alert('提示', '请先保存物品单!');
            return;
        }
        if (!mEvidenceBill.IsCheck) {
            $.messager.alert('提示', '通过审核之后的物品单据才能打印!');
            ret

        }
        window.open("/PrintBill/EvidenceBillPage?EviBillId=" + mEvidenceBill.Id, 'newwindow', 'height=768, width=1024, top=0,left=0,  scrollbars=no, resizable=no,location=no, status=no');
    } catch (ex) {

    } finally {

    }
};
function exit() {
    //top.location.reload();
    parent.art.dialog.list['diaFormStorageView'].close();
    //loadCaseFile();
}

function attachmentAction() {
    if (mEvidenceBill.Id == 0) {
        $.messager.alert('提示', '请先保存物品单据,再添加附件!');
        return;
    } else {
        mDlgAttachment = art.dialog({
            title: '附件管理',
            id: "dlgAttachment",
            content: "<iframe scrolling='yes' frameborder='0' src='/Attachment/AttachmentView?CaseId="+mEvidenceBill.Id+"&billType=1&billId=" + mEvidenceBill.Id + "' style='width:600px;height:360px;'/>",
            lock: true,
            initFn: function () {
            }
        });
    }
}

function addFileAction() {
    $('#fileInput').uploadify('upload', '*');
}


//------------------------


function getCheckState(value, rowData, index) {
    if (value) {
        return '已审核'
    }
    else {
        return '未审核'
    }
}

function getFormatDate(value, rowData, index) {
    if (value) {
        return gFormatDateFormCSharp(value, 'yyyy-MM-dd');
    }
}

function getFormatBillType(value, rowData, index) {
    return gGetBillTypeName(value);


}


function loadOrgsByStorage() {
    var orgs;
    $.ajax({
        url: "/System/LoadOrganizationListByStorage",
        type: "POST",
        dataType: "json",
        async: false,
        success: function (req) {
            orgs = JSON.parse(req.Data);
        }
    });

    return orgs;
}
